<template>
  <div class="front-login-container">
    <el-card class="login-card">
      <div class="title">活动票务商城 - 用户登录</div>
      <el-form 
        ref="loginFormRef"
        :model="loginForm" 
        :rules="loginRules" 
        label-position="top">
        
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="loginForm.username" 
            placeholder="请输入用户名"
            prefix-icon="User" 
            size="large" />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="loginForm.password" 
            type="password" 
            placeholder="请输入密码"
            prefix-icon="Lock" 
            size="large"
            show-password 
            @keyup.enter="handleLogin" />
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            :loading="loading" 
            class="login-button" 
            size="large"
            @click="handleLogin">
            登录
          </el-button>
        </el-form-item>
        
        <div class="login-links">
          <a href="javascript:;" @click="backToHome">返回首页</a>
          <span class="separator">|</span>
          <a href="javascript:;" @click="showRegisterDialog">注册账号</a>
        </div>
      </el-form>
    </el-card>
    
    <!-- 注册对话框 -->
    <el-dialog
      v-model="registerDialogVisible"
      title="用户注册"
      width="540px"
      :close-on-click-modal="false"
      @closed="closeRegisterDialog">
      <RegisterForm ref="registerFormRef" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useFrontUserStore } from '@/store/frontUser'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import RegisterForm from './RegisterForm.vue'

// 表单引用
const loginFormRef = ref(null)
// 路由实例
const router = useRouter()
// 用户存储
const frontUserStore = useFrontUserStore()
// 加载状态
const loading = ref(false)

// 登录表单数据
const loginForm = reactive({
  username: '', 
  password: ''
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 登录方法
const handleLogin = () => {
  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 清除之前可能存在的无效token
        frontUserStore.resetState()
        
        console.log('开始前台登录请求...', loginForm.username)
        const result = await frontUserStore.frontLoginAction(loginForm)
        console.log('前台登录请求完成:', result)
        
        // 确认token已正确存储
        const storedToken = localStorage.getItem('frontToken')
        console.log('保存的token状态:', storedToken ? '已存在' : '不存在')
        
        ElMessage.success('登录成功')
        
        // 修改跳转逻辑，提高可靠性
        if (storedToken) {
          // 确保路由导航生效
          const redirectPath = router.currentRoute.value.query.redirect || '/'
          console.log('登录成功，即将跳转到:', redirectPath)
          
          // 直接使用路由导航到指定页面
          router.push(redirectPath).catch(err => {
            console.error('路由导航错误:', err)
            // 如果导航失败，尝试使用replace
            router.replace('/').catch(e => {
              console.error('替代导航也失败:', e)
              // 最后的备用方案：使用window.location
              window.location.href = '/'
            })
          })
        } else {
          console.error('登录成功但未能获取token')
          ElMessage.warning('登录成功但未能获取token，请尝试重新登录')
        }
      } catch (error) {
        console.error('登录错误:', error)
        
        // 提供更详细的错误信息
        if (error.response) {
          console.error('响应状态:', error.response.status)
          console.error('响应数据:', error.response.data)
          
          const errorMsg = error.response.data && error.response.data.msg 
            ? error.response.data.msg 
            : `服务器错误 (${error.response.status})`
          
          ElMessage.error(`登录失败: ${errorMsg}`)
        } else if (error.request) {
          console.error('请求已发送但无响应')
          ElMessage.error('登录失败: 服务器无响应，请检查网络连接或稍后重试')
        } else {
          ElMessage.error(error.message || '登录失败')
        }
      } finally {
        loading.value = false
      }
    } else {
      ElMessage.warning('请正确填写登录信息')
      return false
    }
  })
}

// 返回首页
const backToHome = () => {
  router.push('/')
}

// 显示注册信息
const showRegisterInfo = () => {
  ElMessage.info('注册功能开发中，请联系管理员获取账号')
}

// 注册相关
const registerDialogVisible = ref(false)
const registerFormRef = ref(null)

// 显示注册对话框
const showRegisterDialog = () => {
  registerDialogVisible.value = true
}

// 关闭注册对话框
const closeRegisterDialog = () => {
  registerDialogVisible.value = false
  // 如果表单引用存在，重置表单
  if (registerFormRef.value) {
    registerFormRef.value.reset()
  }
}
</script>

<style scoped>
.front-login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #EBF4FF 0%, #E6F0FE 100%);
  position: relative;
  overflow: hidden;
}

.login-card {
  width: 450px;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
  background-color: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  position: relative;
  z-index: 1;
  border: none;
  animation: fadeIn 0.5s ease-out;
}

.title {
  text-align: center;
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 30px;
  color: #333;
  position: relative;
  padding-bottom: 15px;
}

.title::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60px;
  height: 3px;
  background: linear-gradient(90deg, #409EFF, #4d7aff);
  border-radius: 3px;
}

.login-button {
  width: 100%;
  height: 45px;
  font-size: 16px;
  font-weight: 500;
  letter-spacing: 1px;
}

.login-links {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
}

.login-links a {
  color: #409EFF;
  text-decoration: none;
  transition: color 0.3s;
}

.login-links a:hover {
  color: #66b1ff;
}

.separator {
  color: #ddd;
  margin: 0 10px;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

@media (max-width: 500px) {
  .login-card {
    width: 90%;
    padding: 20px;
  }
}
</style> 